﻿var nsList = new function () {
	var insertFeature = function (feature, list, indent, hidden) {
		var li = $("<li class='feature'/>");
		var a = $("<a/>");

		a.text(feature.name);
		li.append(a);
		li.css("padding-left", (indent * 20 + 11) + "px");

		if (feature.failed > 0) {
			li.addClass("failed");
		}
		else if (feature.pending > 0) {
			li.addClass("pending");
		}

		li.click(function () {
			showFeature(feature);
		});

		if (hidden) li.css("display", "none");

		list.append(li);

		return li;
	};

	var insertNamespace = function (namespace, list, indent, hidden) {
		var li = $("<li class='namespace'/>");

		li.addClass("namespace");
		li.addClass("collapsed");
		li.text(namespace.name);
		li.css("padding-left", (indent * 20 + 11) + "px");
		li.css("background-position", (indent * 20) + "px center");

		if (namespace.failed > 0) {
			li.addClass("failed");
		}
		else if (namespace.pending > 0) {
			li.addClass("pending");
		}

		if (hidden) li.css("display", "none");

		list.append(li);

		var subelements = [];

		for (var nsIndex in namespace.namespaces) {
			var ns = namespace.namespaces[nsIndex];
			var subelement = insertNamespace(ns, list, indent + 1, true);
			subelements.push(subelement);
		}

		for (var featureIndex in namespace.features) {
			var feature = namespace.features[featureIndex];
			subelement = insertFeature(feature, list, indent + 1, true);
			subelements.push(subelement);
		}

		li.closeNamespace = function () {
			li.removeClass("expanded");
			li.addClass("collapsed");

			for (var subelementIndex in subelements) {
				var sub = subelements[subelementIndex];
				sub.hide();
				if (sub.hasClass("namespace")) {
					sub.closeNamespace();
				}
			}
		};

		li.openNamespace = function () {
			li.removeClass("collapsed");
			li.addClass("expanded");

			for (var subelementIndex in subelements) {
				var sub = subelements[subelementIndex];
				sub.show();
			}
		};

		li.click(function () {
			if (li.hasClass("collapsed")) {
				li.openNamespace();
			}
			else {
				li.closeNamespace();
			}
		});

		return li;
	};

	this.init = function (report, list) {
		for (var i in report.namespaces) {
			var ns = report.namespaces[i];
			insertNamespace(ns, list, 0, false);
		}

		for (var featureIndex in report.features) {
			var feature = report.features[featureIndex];
			insertFeature(feature, list, 0, false);
		}
	};
}